package cn.sixmillions.mb.config;

import cn.sixmillions.mb.pojo.Configuration;
import cn.sixmillions.mb.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析Mapper.xml文件为MappedStatement对象
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        //传递configuration
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);

        //根对象，即mapper标签
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectElementList = rootElement.selectNodes("//select");
        for (Element selectElement : selectElementList) {
            String id = selectElement.attributeValue("id");
            String resultType = selectElement.attributeValue("resultType");
            String parameterType = selectElement.attributeValue("parameterType");
            String sql = selectElement.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            //拼接statementId，设置MappedStatementMap
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
